import Cookies from 'js-cookie'
import Native from '@/service/native'

class TokenServer {
  get token() {
    return this._token || ''
  }

  set token(token) {
    try {
      if (!token) throw new Error('TokenServer set token error: token is null')
      if (typeof token !== 'string') throw new Error('TokenServer set token error: incorrect type')
      this._token = token
    } catch (error) {
      this._token = ''
      throw error
    }
  }

  async getToken (force = false) {
    if (!this.token || force) {
      await this.getTokenByNative()
    }
    return this.token
  }

  async getTokenByNative () {
    const user = await Native.api.getUser()
    this.token = user.ssoToken || user.accessToken
    console.log('token: ', this.token);
    return this.token
  }

  // 安卓环境下 cookie 中的 Token 可能不正确, 建议还是通过 getUser 进行获取
  getTokenByCookie() {
    this.token = Cookies.get('token')
    return this.token
  }
}

export default TokenServer
